package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.common.result.R;
import com.mars.module.admin.entity.SysDictData;
import com.mars.module.admin.entity.SysHouse;
import com.mars.module.admin.mapper.SysDictDataMapper;
import com.mars.module.admin.mapper.SysHouseMapper;
import com.mars.module.admin.request.SysHouseRequest;
import com.mars.module.admin.service.ISysHouseService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 房屋信息业务层处理
 *
 * @author mars
 * @date 2024-01-23
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysHouseServiceImpl implements ISysHouseService {

    private final SysHouseMapper baseMapper;
    private final SysDictDataMapper dictDataMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysHouse add(SysHouseRequest request) {
        SysHouse entity = SysHouse.builder().build();
        BeanUtils.copyProperties(request, entity);
        entity.setStatus("4");//新增后默认未发布
        entity.setCreateTime(LocalDateTime.now());
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysHouseRequest request) {
        SysHouse entity = SysHouse.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysHouse getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<SysHouse> pageList(SysHouseRequest request) {
        Page<SysHouse> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysHouse> query = this.buildWrapper(request);
        IPage<SysHouse> pageRecord = baseMapper.selectPage(page, query);
        List<SysHouse> records = pageRecord.getRecords();
        List<SysHouse> recordsNew = new ArrayList<>();
        for (SysHouse rentRecord : records) {
            rentRecord.setStatus(getStatusName(rentRecord.getStatus(), "house_status"));
            recordsNew.add(rentRecord);
        }
        recordsNew = recordsNew.stream().sorted((m1, m2) -> m2.getCreateTime().compareTo(m1.getCreateTime())).collect(Collectors.toList());
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }

    private String getStatusName(String value, String type) {
        List<SysDictData> reviewStatus = dictDataMapper.selectList(Wrappers.lambdaQuery(SysDictData.class)
                .eq(SysDictData::getDictType, type).orderByAsc(SysDictData::getDictSort));
        SysDictData sysDictData = reviewStatus.stream().filter(e -> value.equals(e.getDictValue())).findFirst().orElse(null);
        return sysDictData == null ? "" : sysDictData.getDictLabel();
    }


    @Override
    public List<SysHouse> list(SysHouseRequest request) {
        LambdaQueryWrapper<SysHouse> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public R publish(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        if (isExistPulish(idList)) {
            for (Long id : idList) {
                SysHouse sysHouse = baseMapper.selectById(id);
                if (sysHouse != null) {
                    sysHouse.setStatus("3");//已发布
                    baseMapper.updateById(sysHouse);
                }
            }
            return R.success();
        } else {
            return R.error("500", "只能发布未发布的房屋！");
        }
    }

    public boolean isExistPulish(List<Long> idList) {
        boolean flag = true;
        for (Long id : idList) {
            SysHouse sysHouse = baseMapper.selectById(id);
            if (sysHouse != null && !"4".equals(sysHouse.getStatus())) {
                flag = false;
            }
        }
        return flag;
    }

    public boolean isExist(List<Long> idList) {
        boolean flag = true;
        for (Long id : idList) {
            SysHouse sysHouse = baseMapper.selectById(id);
            if (sysHouse != null && !"3".equals(sysHouse.getStatus())) {
                flag = false;
            }
        }
        return flag;
    }

    @Override
    public R offShelf(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        if (isExist(idList)) {
            for (Long id : idList) {
                SysHouse sysHouse = baseMapper.selectById(id);
                if (sysHouse != null) {
                    sysHouse.setStatus("4");//已发布
                    baseMapper.updateById(sysHouse);
                }
            }
            return R.success();
        } else {
            return R.error("500", "只能下架已发布的房屋！");
        }
    }

    private LambdaQueryWrapper<SysHouse> buildWrapper(SysHouseRequest param) {
        LambdaQueryWrapper<SysHouse> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getHouseName())) {
            query.like(SysHouse::getHouseName, param.getHouseName());
        }
        if (StringUtils.isNotBlank(param.getArea())) {
            query.like(SysHouse::getArea, param.getArea());
        }
        if (param.getPrice() != null) {
            query.like(SysHouse::getPrice, param.getPrice());
        }
        if (StringUtils.isNotBlank(param.getAddress())) {
            query.like(SysHouse::getAddress, param.getAddress());
        }
        if (StringUtils.isNotBlank(param.getStatus())) {
            query.like(SysHouse::getStatus, param.getStatus());
        }
        if (StringUtils.isNotBlank(param.getPicture())) {
            query.like(SysHouse::getPicture, param.getPicture());
        }
        return query;
    }

}
